﻿using Ewell.Interface.Common.Model.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ewell.Interface.Common.Utils
{
    public class FileReaderHelper
    {
        /// <summary>
        /// 读取文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        /// <exception cref="SpeedException"></exception>
        public static IEnumerable<string> ReadLines(string filePath)
        {
            if (!File.Exists(filePath))
            {
                throw new SpeedException("文件不存在!"+filePath);
            }

            using (StreamReader reader = new StreamReader(filePath))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    yield return line;
                }
            }
        }
        /// <summary>
        /// 按行读取文件并执行委托
        /// </summary>
        /// <param name="filePath">文件名</param>
        /// <param name="lineCount">读取行数</param>
        /// <param name="processLine">每读取N行执行的方法</param>
        /// <exception cref="SpeedException"></exception>
        public static void ReadLines(string filePath,int lineCount, Action<List<string>> processLine)
        {
            if (!File.Exists(filePath))
            {
                throw new SpeedException("文件不存在!"+ filePath);
            }

            List<string> lines = new List<string>();

            using (StreamReader reader = new StreamReader(filePath))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    lines.Add(line);

                    if (lines.Count == lineCount)
                    {
                        processLine(lines);
                        lines.Clear();
                    }
                }
            }
            if(lines?.Count > 0) processLine(lines);
        }
    }
}
